package trefliq.EJB.mdb;

import java.util.Date;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.embeddable.EJBContainer;
import javax.jms.*;
import javax.naming.*;

/**
 *
 * @author Adam
 */
public class NewMovieReceiver {
    private Context _JndiContext;
    private ConnectionFactory _ConnectionFactory; 
    private Topic _NewMovieTopic; 
 
    private static EJBContainer _ec;

    public NewMovieReceiver() throws NamingException {
        //maybe need to move this to abstract class...
        _ec = EJBContainer.createEJBContainer();
        _JndiContext = _ec.getContext();
        
        //get the topic and stuff
        _ConnectionFactory = (ConnectionFactory) _JndiContext.lookup("jms/trefliq/ConnectionFactory");
        _NewMovieTopic = (Topic) _JndiContext.lookup("jms/trefliq/TopicNewMovieIn");   
 
    }

    public boolean CheckForNewMovie() throws JMSException {
        // Connect to topic to add message
        Connection connection = _ConnectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(_NewMovieTopic);
        
        // get topic message
        connection.start();
        
//        while (true) {
            TextMessage message = (TextMessage) consumer.receive(3000L); //wait 3 sec
            if (message != null) {
                System.out.println("Message received: " + message.getText());
            }
            else {
                System.out.println("No message received.");                
            }
//            consumer.receiveNoWait()
//        }
        // Clean up
        connection.close();
        
        return true;
    }
    
 }
